<?php

use App\Models\Agent;

require __DIR__ . '/../vendor/autoload.php';

$app = require_once __DIR__ . '/../bootstrap/app.php';

$app->make(\App\Console\Kernel::class)->bootstrap();

/* ============== Write Codes Below ================= */

echo '>>> Start Laravel from CLI' . PHP_EOL;

$agents = Agent::query()->get();

/** @var Agent $agent */
foreach ($agents as $agent) {
    //查询代理是否有默认门店
    $store = \App\Models\Store::query()->where('agent_id', $agent->id)->where('is_default', true)->first();
    if (!$store) {
        //查询关联的发行平台账号
        $mobile = \App\Models\AgentConfig::getConfig($agent->id, 'pub_account');
        if ($mobile) {
            $store = new \App\Models\Store();
            $store->agent_id = $agent->id;
            $store->name = $agent->name;
            $store->mobile = $mobile;
            $store->is_default = true;
            $store->save();
            echo sprintf('代理[%s]自动创建门店，手机号%s', $agent->name, $mobile) . PHP_EOL;
        } else {
            echo sprintf('代理[%s]未关联发行平台账号，不自动创建门店', $agent->name) . PHP_EOL;
        }
    } else {
        echo sprintf('代理[%s]已存在默认门店，不自动创建门店', $agent->name) . PHP_EOL;
    }

    if ($store) {
        //查询代理下的商品，将所属门店设置为当前默认门店
        $count = \App\Models\Product::query()->where('agent_id', $agent->id)
            ->where('store_id', 0)
            ->update([
                'store_id' => $store->id,
            ]);

        echo sprintf('商品所属门店自动修改为默认门店，修改商品数量', $count) . PHP_EOL;
    }
}
